<template>
	<view class="box">
		<view class="fontweight">拍照上传</view>
		<span >请讲工作轨迹、成果、客户签字确认拍照上传</span>
		<view class="content1">
			<p>工作轨迹、成果:</p>
			<view>
				<u-upload
						:fileList="fileList1"
						@afterRead="afterRead"
						@delete="deletePic"
						name="1"
						multiple
						:maxCount="3"
					></u-upload>
			</view>
			
		</view>  
		<view class="content1">
			<p>服务完成照:</p>
			<view>
				<u-upload
					:fileList="fileList2"
					@afterRead="afterRead"
					@delete="deletePic"
					name="2"
					multiple
					:maxCount="1"
					:previewFullImage="true"
				></u-upload>
			</view>
		</view>
		<view class="bottom" v-if="orderForm.managementPayType==1">
			<view class="fontweight">尾款设置</view>{{orderForm.orderNo}}:{{orderForm.id}}
			<uni-forms ref="valiForm"  :modelValue="orderForm"  :rules="rules" label-width="80" size="mini">
				<uni-forms-item label="尾款金额:"  name="tailMoneya">
					<uni-easyinput @input="onInput" v-model="orderForm.finalPrice" placeholder="请输尾款金额"  />
				</uni-forms-item>
				<uni-forms-item label="预约金额:"  >
					<uni-easyinput disabled v-model="(orderForm.appointmentPrice/100).toFixed(2)" placeholder="金额获取异常" />
				</uni-forms-item>
				<uni-forms-item label="订单总额:" >
					<uni-easyinput disabled v-model="(orderForm.totalPrice/100+Number(orderForm.finalPrice)).toFixed(2)" placeholder="金额获取异常" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<!-- 线下单 技师可以帮客户预约  type：1线下单 0线上单-->
		 <!-- <view v-if="orderForm.type==1" class="reservation">
			<checkbox-group>
				<checkbox type="checkbox"  :checked='reservation' @click="reservation = !reservation" color="#09CC86"/>
				是否预约下次服务
			</checkbox-group>
			<view v-if="reservation">
				<u--form labelPosition="left":model="reservationForm" 	:rules="rules"	ref="uForm" labelWidth="80">
					<u-form-item label="预约时间" borderBottom @click="openTime">
						<u--input v-model="reservationForm.appointmentTime"	disabled disabledColor="#ffffff" placeholder="请选择服务类型" border="none"></u--input>
						<u-icon	slot="right"	name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="服务类型"	prop="reservationForm.homemakingName"	borderBottom	ref="item1"
						@click="pickerType(1)"
					>
						<u--input v-model="reservationForm.homemakingName"	disabled disabledColor="#ffffff" placeholder="请选择服务类型" border="none"></u--input>
						<u-icon	slot="right"	name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="服务名称"	prop="reservationForm.name"	borderBottom	ref="item1"
						@click="pickerType(2)"
					>
						<u--input v-model="reservationForm.serveName"	disabled disabledColor="#ffffff" placeholder="请选择服务名称" border="none"></u--input>
						<u-icon	slot="right"	name="arrow-right"></u-icon>
					</u-form-item>
				</u--form>
			</view>
			<u-picker :show="pickerShow" :columns="pickerData" keyName="name" @cancel="pickerClose" @confirm="pickerClick"></u-picker> -->
			<!-- 上门时间选择 -->
			<!-- <uni-popup ref="popup" type="bottom" background-color="#fff">
				<view>
					<prettytimes @change="getprettytimes" Days="5"  beginTime="06:00:00" endTime='23:00:00' :timeInterval="1" :isQuantum="true" ></prettytimes>
				</view>
			</uni-popup>
		</view> -->
		<u-button type="primary" shape="circle"size="small" text="提交" @click="submitFinalPrice('valiForm')"
			 color="linear-gradient(to right, rgb(254, 223, 77), rgb(255, 211, 77))"
		></u-button>
		<view style="height: 1px;"></view>
	</view>
</template>

<script>
	import prettytimes from '@/components/pretty-times/pretty-times.vue';
	export default {
		components: {
		    prettytimes
		},
		data() {
			return {
				isAll:null,
				reservation:false,
				pickerShow:false,
				pickerNum:1,//标签
				pickerData:[],
				Days:5,//日期可选天数
				fileList1: [],
				fileList2:[],
				orderForm:{
					type:1,
					zong:"20",
					pointmentMoneya:"20",
					tailMoneya:"",
				},
				homemakingTypedata:[],
				serveNamedata:[],
				serveNamelist:[],
				//预约表单
				reservationForm:{
					serveId:"",
					serveName:"",
					homemakingType:"",//家政类型id
					homemakingName:"",
					appointmentTime:"",
				},
				rules: {
					tailMoneya: {
						rules: [{	required: true,	errorMessage: '请输入尾款金额'}, 
					        	{format: 'number',    errorMessage: '请输入数字'},
								{
										validateFunction:function(rule,value,data,callback){
											let iphoneReg = /^(\d?)+(\.\d{0,2})?$/;
											if (!iphoneReg.test(value)) {
												callback('金额小数点后不能大于两位数') 
											}
											if (value==0) {
												callback('请输入尾款金额')
											}
											return true 
										}
									}
								]
					},
					
				},
			}
		},
		onLoad(e) {
			console.log(JSON.stringify(e.orderId))
			console.log(JSON.stringify(e.id))//84：13
			this.show(e.orderId,e.id)
			this.homemakingTypeShow()
			this.serviceName()
		},
		methods: {
			numberFixedDigit (e) { // 固定两位小数
			  e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || ''
			  this.$nextTick(() => {
			    this.number= e.target.value
			  })
			},
			show(orderId,dispatchRecordId){
				this.request.getRequest(this.http.httpsLian.homemakingOrderGetId,{id:orderId})
				.then(res => { 
					console.log("res",res)
					if(res.code!=0 )return 
					this.orderForm = res.data;
					this.orderForm.finalPrice=(this.orderForm.finalPrice/100).toFixed(2);
					this.orderForm.dispatchRecordId = dispatchRecordId // 派单记录ID
					this.isAll = this.orderForm.managementPayType == 0 ? true : false;//是否全款
				}).catch(res => {
					uni.$u.toast(res)
				})
			},
			//提交尾款
			submitFinalPrice(ref){
				
				if(this.fileList1.length==0){
					uni.$u.toast("请上传工作轨迹、成果图")
					return;
				}
				if(this.fileList2.length==0){
					uni.$u.toast("请上传客户签字确认单")
					return;
				}
				if(this.orderForm.type==1){
					if(this.reservation){
						if(this.reservationForm.appointmentTime==""){
							uni.$u.toast("请选择预约时间")
							return;
						}
						if(this.reservationForm.homemakingName==""){
							uni.$u.toast("请选择服务类型")
							return;
						}
						if(this.reservationForm.serveName==""){
							uni.$u.toast("请服务名称")
							return;
						}
						
					}
				}
				
				let datas=JSON.parse(JSON.stringify(this.orderForm))
				/* datas.workingAchievementPicUrl=this.fileList1
				datas.signaturePicUrl=this.fileList2 */
				datas.workingAchievementPicUrl=JSON.stringify(this.fileList1)
				datas.signaturePicUrl=JSON.stringify(this.fileList2)
				datas.isAll=this.isAll
				
				let msg;
				//type订单类型 （0线上订单、1线下订单，2vip免费用户
				if(this.orderForm.type==0){
				
					if(!this.isAll){
					 // 单位转换
					 datas.finalPrice=Number(this.orderForm.finalPrice*100)
					 //console.log("datas.finalPrice",datas.finalPrice)
					 msg = '尾款已提交，等待客户支付尾款'
					 this.$refs[ref].validate().then(res => {
										  
						this.post(datas,msg)
					 }).catch(err => {
						console.log('err', err);
					 })
					}else{
					  
					  msg = '服务已完成'
					  datas.finalPrice=0;
					  console.log("服务已完成",JSON.stringify(datas))
					  this.post(datas,msg)
					}
				}else{
					msg = '服务已完成'
					datas.finalPrice=0;
					console.log("服务已完成",JSON.stringify(datas))
					this.post(datas,msg)
				}
				//this.postReservation()
				
			},
			post(datas,msg){
				let this_=this
				this.request.postRequest(this.http.httpsLian.homemakingOrderSubmitFinalPrice,datas,true)
				.then(res => { 
					console.log("尾款返回:"+JSON.stringify(res))
					let iconMsg;
					if(res.code==0)iconMsg=true;
					if(res.code!=0)iconMsg=false;
					uni.showToast({
						title:iconMsg?msg:'提交失败',
						icon:iconMsg?"success":"error",
						duration: 1800
					})
					if(res.code==0){
						if(this_.orderForm.type==1){
							if(this_.reservation){
								this_.postReservation()
							}
						}	
						setTimeout(() => {
							var pages = getCurrentPages(); // 获取当前挂载的路由数组
							var prePage = pages[pages.length - 2] //获取 上一个页面
							uni.navigateBack({
								data:1,
								success(event) {
									prePage.$vm.reload() // 当返回成功的时候调用上一级页面的回调
								}
							})
						}, 1900)
						
					}
					
					 
				}).catch(res => {
					uni.$u.toast("连接异常10")
				})
			},
			//提交预约服务
			postReservation(){
				//console.log("原来单的数据",this.orderForm)
				
				let data=JSON.parse(JSON.stringify(this.orderForm))
				let data2=JSON.parse(JSON.stringify(this.orderForm))
				
				data.serveId=this.reservationForm.serveId
				data.serveName=this.reservationForm.serveName
				data.homemakingType=this.reservationForm.homemakingType;//家政类型id
				data.appointmentTime=this.reservationForm.appointmentTime
				data.orderTime=this.utils.dateFormat(new Date())
				data.orderStatus=1;//平台派单状态
				data.orderReceivingStatus=0;//技师接单状态设置为 未接单1.
				
				//默认
				data.orderReceivingTime="";
				data.creator="";
				data.createTime="";
				data.updater="";
				data.updateTime="";
				data.finalPrice=0
				data.adminOrderType=0
				
				data.storeId=""
				data.storeOrTechnicianName=""
				
				data.technicianAge=""
				data.technicianId=""
				data.technicianLevel=""
				data.technicianLevelId=""
				data.technicianName=""
				data.technicianPhone=""
				
				/* data.userId=this.orderForm.imageUrl
				data.userName=this.orderForm.imageUrl
				data.userPhone=this.orderForm.imageUrl
				data.storeId=this.orderForm.storeId
				data.storeOrTechnicianName=this.orderForm.storeOrTechnicianName
				data.technicianId=this.orderForm.technicianId */
				//console.log("新单的数据",data)
				let this_=this
				this.request.postRequest(this.http.httpsLian.homemakingCreate,data)
				.then(res => { 
					if(res.code==0){
						//console.log("预约单提交返回:"+JSON.stringify(res))
						data.id=res.data
						//console.log("派单记录",data2)
						data.storeId=data2.storeId
						data.storeOrTechnicianName=data2.storeOrTechnicianName
						
						data.technicianAge=data2.technicianAge
						data.technicianId=data2.technicianId
						data.technicianLevel=data2.technicianLevel
						data.technicianLevelId=data2.technicianLevelId
						data.technicianName=data2.technicianName
						data.technicianPhone=data2.technicianPhone
						data.adminOrderType=5
						//console.log("派单记录data2",data)
						this_.dispatchRecord(data) 
					}
				}).catch(res => {
					uni.$u.toast("预约单失败，请使用后台重新派单")
				})
			},
			//提交派单记录
			dispatchRecord(data){
				this.request.postRequest(this.http.httpsLian.homemakingsubOrder,data)
				.then(res => { 
					console.log("预约单提交返回:"+JSON.stringify(res))
					 
				}).catch(res => {
					uni.$u.toast("连接异常10")
				})
			},
			//打开时间选择器
			openTime(){
				this.$refs.popup.open('bottom')
			},
			//选中的时间
			getprettytimes(e){
				console.log(e)
				// 关闭窗口后，恢复默认内容
				this.reservationForm.appointmentTime=e.beginAndend;
				this.$refs.popup.close()
			},
			//点击服务类型
			pickerType(type){
				this.pickerNum=type
				if(this.pickerNum==1){
					this.pickerData=this.homemakingTypedata
					
				}else{
					this.pickerData=this.serveNamelist
				}
				this.pickerShow=true
			},
			//点击家政类型确认
			pickerClick(e){
				console.log(e)
				if(this.pickerNum==1){
					this.serveNamelist=[]
					this.reservationForm.homemakingName=e.value[0].name
					this.reservationForm.homemakingType=e.value[0].id
					//根据家政分类id 筛选 服务名称数据
					let data =this.serveNamedata.filter(el=>el.homemakingType==e.value[0].id)
					this.serveNamelist.push(data)
					this.reservationForm.serveName=""
					this.reservationForm.serveId=""
					console.log("根据家政分类id 筛选 服务名称数据",this.serveNamelist)
				}else{
					this.reservationForm.serveName=e.value[0].name
					this.reservationForm.serveId=e.value[0].id
				}
				this.pickerShow=false
			},
			//点击服务名称确认
			pickerServeName(e){
				console.log(e)
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			onInput(newVal){
				this.orderForm.zong=Number(this.orderForm.pointmentMoneya)+Number(newVal)
			},
			//查询家政类型
			homemakingTypeShow(){
				this.request.getRequest(this.http.httpsLian.homemakingtypelist,{parentId: 28,status:0})
				.then(res => { 
					if(res.code!=0 )return 
					let data=[]
					data.push(res.data)
					this.homemakingTypedata=data
					console.log("查询家政类型homemakingTypedata",this.homemakingTypedata)
				}).catch(res => {
					uni.$u.toast(res)
				})
			},
			//查询服务名称
			serviceName(){
				this.request.getRequest(this.http.httpsLian.managementlist)
				.then(res => { 
					if(res.code!=0 )return 
					//let data=[]
					//data.push(res.data)
					this.serveNamedata=res.data
					console.log("查询服务名称serveNamedata",this.serveNamedata)
				}).catch(res => {
					uni.$u.toast(res)
				})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			//图片上传    
			uploadFilePromise(url,name) {
				let _this=this
				let token = uni.getStorageSync("token");
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						//url: this.$common.domain+'/api/common/upload', // 仅为示例，非真实的接口地址
						url:this.http.httpsLian.upload, // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							'tenant-id': 1,
							//"content-type": "application/json",//"Content-Type": "multipart/form-data",
							"Authorization": "Bearer "+token
						},
						name: 'file',
						success: (res) => {
							let data =JSON.parse(res.data)
							if(data.code!=0){
								setTimeout(() => {
								const num = _this[`fileList${name}`].findIndex(v => v.url === url);
									_this[`fileList${name}`].splice(num, 1);
								}, 500)
								uni.$u.toast("上传失败")
								return
							}
							//uni.$u.toast("上传成功")
							resolve(data.data)
							
						}
					});
				})
			},    
			
			//唤醒手机拍照  
			chooseImage(){
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'],   //album 从相册选图，camera 使用相机
					success: function (res) {
						console.log(JSON.stringify(res.tempFilePaths)); //拍照图片的路径
						this.fileList3.push({
							url:res.tempFilePaths
						})
					}
				});
			},
			pickerClose(){
				this.pickerShow=false;
			}
		}
	}
</script>

<style lang="scss" scoped>
.box{
	margin-top: 10rpx;
	padding: 0px 10px;
	//background-color: white;
}	
.fontweight{
	font-weight: 550;
}
.content1{
	margin-top: 20px;
	/deep/.u-upload__button{
		background-color: white;
		
	}
	view{
		margin-top: 10px;
	}
}
span{
	font-size: 11px;
	color: $uni-text-color-grey;
}
p{
	font-size: 12px;
}
.bottom{
	background: white;
	padding: 10px;
	
	/deep/.u-input{
		width: 120px !important;
		//background-color: rgb(245, 247, 250);
	}
	
	.fontweight{
		margin-bottom: 20px;
	}
}
/deep/.u-button{
	    color: black !important;
		margin-top: 20px;
		margin-bottom: 20px;
	}
	.reservation{
		background-color: white;
		padding: 10px 0px;
	}
</style>
